package com.ruoyi.system.domain;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class JsonToArrayListTypeHandler extends BaseTypeHandler<String[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (Exception e) {
            throw new SQLException("Failed to convert array to JSON string", e);
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json == null || json.isEmpty()) return new String[0];
        try {
            List<String> list = objectMapper.readValue(json, new TypeReference<List<String>>() {});
            return list.toArray(new String[0]);
        } catch (Exception e) {
            throw new SQLException("Failed to parse JSON to array", e);
        }
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        if (json == null || json.isEmpty()) return new String[0];
        try {
            List<String> list = objectMapper.readValue(json, new TypeReference<List<String>>() {});
            return list.toArray(new String[0]);
        } catch (Exception e) {
            throw new SQLException("Failed to parse JSON to array", e);
        }
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        if (json == null || json.isEmpty()) return new String[0];
        try {
            List<String> list = objectMapper.readValue(json, new TypeReference<List<String>>() {});
            return list.toArray(new String[0]);
        } catch (Exception e) {
            throw new SQLException("Failed to parse JSON to array", e);
        }
    }
}